package com.bjpower.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.bjpower.models.request.ShopInfoRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;


@Controller
public class shopController {
    @GetMapping("/create/order")
    public String createOrder(ShopInfoRequest shopInfoRequest, Model model){
        //创建快钱需要的信息 并按照字典进行排序
        String userNo = "81764817292347027458";
        String appKey = "55bd6e4d47d9736b140f79bf46d61c97";
        String productCode = "cp01";
        String pageUrl = "http://localhost:8020/show.html";
        //商家异步通知地址
        String notifyUrl = "http://localhost:8010/handle/notice";
        String appSecret = "8e693ba35bc9827fb8d45e2229ce3ecf";
        String orderNo = "ShopA" +  new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.randomNumbers(6);
        //将shopInfoRequest转换为map存放到map集合中进行排序
        String jsonStr = JSONUtil.toJsonStr(shopInfoRequest);
        Map beanMap = JSONUtil.toBean(jsonStr, Map.class);
        beanMap.put("userNo",userNo);
        beanMap.put("appKey",appKey);
        beanMap.put("productCode",productCode);
        beanMap.put("pageUrl",pageUrl);
        beanMap.put("notifyUrl",notifyUrl);
        beanMap.put("orderNo",orderNo);

        TreeMap<String, String> treeMap = new TreeMap<>(beanMap);

        //将非空字段拼接成&userNo：....&appKey:...的格式
        StringBuilder stringBuilder = new StringBuilder();
        treeMap.forEach((key, value) -> {
            if(StrUtil.isNotBlank(value)){
                stringBuilder.append(key).append("=").append(value).append("&");
            }
        });
        stringBuilder.append("appSecret").append("=").append(appSecret);
        //将字符串进行md5加密
        String md5Hex = DigestUtil.md5Hex(stringBuilder.toString());
        beanMap.put("sign",md5Hex);
        model.addAllAttributes(beanMap);
        //返回视图
        return "createOrder";
    }
}
